const app = getApp();
let getlogininfo = require('../trtc/getlogininfo');
const rtcroom = require('../trtc/utils/rtcroom');
const {
  getOpenID,
  getUserInfoWidthCredentials,
} = require('../../common/utils/ws/wsxcx-opendata-sdk');
const { config } = require('../../common/utils/ws/ws-config.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userName: '',
    isGetLoginInfo: false,  // 是否已经获取登录信息
    firstshow: true, // 第一次显示页面
    tapTime: {}, // 防止两次点击操作间隔太快
    canShow: false,
    isAdmin: false,  // 是否为管理员 默认false
    isCertification: false,  // 是否认证过 默认false
    total: 0,  // 在线客服数
    isShowNoti: true,
    isSetting: false, // 验证配置
    isServer: false, // 验证服务
    checkingIdentity: true,
    checkingCertification: true,
    showHomeBtn: app.siteInfo.module !== 'ws_empty',
    floatItems:[{
      type: 10, // 自定义事件
      show: true,
      iconClass:'icon icon-icon-default-headerl',
    },{
      type: 0, // 自定义事件
      show: true,
      iconClass: 'icon icon-sy',
      event: 'myEvent2',
    }],
  },

  /**
   * 生命周期函数--监听页面加xin
   */
  onLoad: function(options) {
    // this.setData({
    //   roomID: options.roomID || '',
    //   roomName: options.roomName || '',
    //   userName: options.userName || '',
    // })
    // if (options.roomID && options.roomName && options.userName) {
    //   wx.navigateTo({
    //     url: `/cm_video_alarm/trtc/pages/customer-service-room/customer-service-room?roomID=${options.roomID}&roomName=${options.roomName}&userName=${options.userName}`,
    //   });
    // }

    // 测试直播配置
    this.checkImSetting();
  },

  // 测试配置
  checkImSetting() {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'checkImSetting',
        uniacid: `${config.uniacid}`
      },
      module: 'cm_trtc',
      success: res => {
        let { errno, data: { msg: errMsg } } = res.data;
        if (errno) {
          wx.showModal({
            title: '提示',
            content: errMsg,
            showCancel: false,
            success: res => {
              wx.navigateBack({});
            }
          })
          return;
        } else {
          this.setData({
            isSetting: true
          })
          // 测试直播服务
          this.checkNode();
        }
      }
    })
  },
  // 测试直播服务是否开启
  checkNode(){
    app.util.request({
      url:'entry/wxapp/index',
      data:{
        op:'checkNode',
        uniacid: `${config.uniacid}`
      },
      module:'cm_trtc',
      success: res=>{
        let { errno, data:{msg: errMsg} } = res.data;
        if(errno) {
          wx.showModal({
            title: '提示',
            content: errMsg,
            showCancel: false,
            success: res =>{
              wx.navigateBack({});
            }
          })
          return;
        } else {
          this.setData({
            isServer: true
          })
          this.onShow();
        }
      }
    })
  },

  go_home(){
    const isCompanyCloudTemplate = Number(app.siteInfo.isCloudTemplate) === 1;
    if (isCompanyCloudTemplate) {  // 企业云端发布
      app.util.navigateTo('ws_micro_company_collection/pages/index/index', '', true);
      return;
    }
    let appJson = app.siteInfo.appJson[app.tabbarindex || 0];
    const url = appJson.homePage || (appJson.tabBar && appJson.tabBar.list && appJson.tabBar.list[0].pagePath);
    app.util.navigateTo(url, {}, 'all');
  },
  collectformid(e) {
    let formid = e.detail.formId;
    let openid = wx.getStorageSync('openid') || wx.getStorageSync('wsOpenID') || wx.getStorageSync('OPENID');
    app.util.request({
      url: 'pushService/api/formid',
      data: {
        formid,
        openid,
      },
      method: 'GET',
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if (wx.createLivePlayerContext) {
      this.setData({
        canShow: true,
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后再试。',
        showCancel: false,
      });
    }
    // 先获取登录信息
    let self = this;
    wx.showLoading({
      title: '登录信息获取中',
    });
    getlogininfo.getLoginInfo({
      type: 'multi_room',
      success: function (ret) {
        self.setData({
          firstshow: false,
          isGetLoginInfo: true,
        });
        console.log('我的昵称：', ret.userName);
        self.setData({
          userName: ret.userName,
        });
        wx.hideLoading();
        const { roomID= '', roomName = '', userName = '' } = self.options;
        if (roomID && roomName && userName) {
          wx.navigateTo({
            url: `/cm_video_alarm/trtc/pages/customer-service-room/customer-service-room?roomID=${roomID}&roomName=${roomName}&userName=${userName}`,
          });
        }
      },
      fail: function (ret) {
        self.setData({
          isGetLoginInfo: false,
        });
        wx.hideLoading();
        wx.showModal({
          title: '获取登录信息失败',
          content: ret.errMsg,
          showCancel: false,
          complete: function () {
            wx.navigateBack({});
          },
        });
      },
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let { isSetting, isServer } = this.data;
    if (isSetting && isServer){
    this.initInfo();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    rtcroom.logout();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.initInfo();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },

  getUsername(userInfo) {
    return new Promise(resolve => {
      if (this.data.isCertification) {
        app.util.request({
          url: 'entry/wxapp/user',
          data: {
            op: 'getUser',
          },
          module: 'cm_video_alarm',
          success: res => {
            let name = res.data.data && res.data.data.name;
            resolve(name);
          },
        });
      } else {
        resolve(userInfo.nickName || this.data.userName);
      }
    });
  },

  call: function (e) {
    if (e.detail.errMsg === 'getUserInfo:ok') {
      getUserInfoWidthCredentials(e.detail);
    }
    const {
      total,
      isDemonstration,
    } = this.data;
    const userInfo = e.detail.userInfo;
    // 防止两次点击操作间隔太快
    const nowTime = new Date();
    if (nowTime - this.data.tapTime.call < 1000) {
      return;
    }
    if (!this.data.isGetLoginInfo || this.data.checkingCertification) {
      wx.showModal({
        title: '提示',
        content: '登录信息初始化中，请稍后再试',
        showCancel: false,
      });
      return;
    }
    if (!isDemonstration && total <= 0) {
      wx.showModal({
        title: '温馨提示',
        content: '坐席繁忙，请直接客服电话',
        showCancel: false,
      });
      return;
    }
    this.getAuthorization().then(() => {
      if (this.data.canShow) {
        this.getUsername(userInfo).then(userName => {
        const url = `/cm_video_alarm/trtc/pages/call/call?userName=${userName}`;
        app.util.navigateTo(url);
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后再试。',
          showCancel: false,
        });
      }
    });
    this.setData({
      'tapTime.call': nowTime,
    });
  },

  police: function (e) {
    if (e.detail.errMsg === 'getUserInfo:ok') {
      getUserInfoWidthCredentials(e.detail);
    }
    const userInfo = e.detail.userInfo;
    const nowTime = new Date();
    if (nowTime - this.data.tapTime.police < 1000) {
      return;
    }
    if (!this.data.isGetLoginInfo) {
      wx.showModal({
        title: '提示',
        content: '登录信息初始化中，请稍后再试',
        showCancel: false,
      });
      return;
    }
    this.getAuthorization().then(() => {
      this.getUsername(userInfo).then(userName => {
      app.util.navigateTo(`/cm_video_alarm/trtc/pages/roomlist/roomlist?userName=${userName}`);
      });
    });
    this.setData({
      'tapTime.police': nowTime,
    });
  },
  initInfo() {
    this.checkIdentity();
    this.checkCertification();
    this.getPoliceOnlineNumber();
    this.getBaseInfo();
  },

  safeRequest(fn) {
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('wsOpenID');
    if (openid) {
      fn && fn(openid);
    } else {
      getOpenID({
        mode: 1,
      }).then((openid) => {
        fn(openid);
      });
    }
  },

  checkCertification() {  // 检查是否认证
    const doRequest = openid=> {
      app.util.request({
        url: 'entry/wxapp/user',
        data: {
          op: 'checkRealName',
          openid,
        },
        module: 'cm_video_alarm',
        success: res => {
          console.log('this: ', this);
          let {
            is_realName: isCertification = '',
          } = res.data.data;
          isCertification = isCertification === 1 ? true : false;
          
          this.setData({
            isCertification,
            checkingCertification: false,
          });
        },
      });
    };
    this.safeRequest(doRequest);
  },
  
  checkIdentity() {  // 检查是否为管理员
    getOpenID({
      mode: 1,
    }).then(openid => {
      app.util.request({
        url: 'entry/wxapp/index',
        data: {
          op: 'checkAdmin',
          openid,
        },
        module: 'cm_video_alarm',
        success: res => {
          let {
            is_admin: status = 0,
          } = res.data.data;
          let isDemonstration = false;
          let isAdmin = false;
          switch (Number(status)) {  // 0: 游客 1：管理员 2：演示模式
            case 1:
              isAdmin = true;  
              break;
            case 2:
              isDemonstration = true;
              break;
            default:
              isAdmin = false; 
              isDemonstration = false; 
              break;
          }
          this.setData({
            isAdmin,
            isDemonstration,
            checkingIdentity: false,
          });
        },
      });
    });
  },
  getPoliceOnlineNumber() {  // 获取在线客服数
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'policeOnline',
      },
      module: 'cm_video_alarm',
      success: res => {
        let {
          total = 0,
        } = res.data.data;
        this.setData({
          total,
        });
      },
    });
  },
  toUserCenter(e) {
    if (e.detail.errMsg === 'getUserInfo:ok') {
      getUserInfoWidthCredentials(e.detail);
    }
    const {
      isCertification,
      isAdmin,
      checkingCertification,
      checkingIdentity,
    } = this.data;
    if (checkingCertification || checkingIdentity) {
      wx.showModal({
        title: '提示',
        content: '登录信息初始化中，请稍后再试',
        showCancel: false,
      });
      return;
    }
    if (isCertification) {
      wx.navigateTo({
        url: `/cm_video_alarm/user-center/user-center?isAdmin=${isAdmin}`,
      });
    } else {
      wx.navigateTo({
        url: '/cm_video_alarm/certification/certification',
      });
    }
  },
  phoneCall: function () {
    let {
      phonenumber: phoneNumber = '',
    } = this.data;
    wx.makePhoneCall({
      phoneNumber,
    });
  },
  getAuthorization: function () {
    return new Promise((resolve) => {
      wx.getSetting({
        success(res) {
          const scopes = ['scope.userLocation', 'scope.record', 'scope.camera'];
          const promises = [];
          for (let i = 0; i < scopes.length; i++) {
            const scope = scopes[i];
            if (!res.authSetting[scope]) {
              promises.push(new Promise((resolve, reject) => {
                wx.authorize({
                  scope,
                  success: function () {
                    resolve();
                  },
                  fail: function (e) {
                    reject(e);
                  },
                });
              }));
            }
          }
          Promise.all(promises).then(() => {
            resolve();
          });
        },
      });
    });
  },
  closeNoti() {
    let {
      isShowNoti,
    } = this.data;
    this.setData({
      isShowNoti: !isShowNoti,
    });
  },
  getBaseInfo() {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'getBase',
      },
      module: 'cm_video_alarm',
      success: res => {
        if(!res.data.data){
          wx.setStorageSync('alarmBaseInfo',{});
          return;
        }
        wx.setStorageSync('alarmBaseInfo', res.data.data);
        let { 
          notice = '',
          title = '',
          banner = '',
          request_title = '',
          recept_title = '',
          phonenumber = '',
        } = res.data.data;

        wx.setNavigationBarTitle({
          title,
        });

        this.setData({
          notice,
          title,
          banner,
          request_title,
          recept_title,
          phonenumber,
        });
      },
    });
  },

  onShareAppMessage(){
    return {
      title: '分享我的视频服务',
      path: 'cm_video_alarm/index/index',
      imageUrl: this.data.banner
    }
  },

  getSubscriptionMessage() {
    let that = this;
    return new Promise(()=>{
      app.util.request({
        url: 'auth/subscribe/getTmplIds',
        data: { m:'cm_video_alarm'},
        success: res => {
          if (res.data.errno === 0) {
            let tmpId = [res.data.message.tmplids];
            wx.requestSubscribeMessage({
              tmplIds: tmpId,
              success: res => {
                console.log('success', res)
                if (res.errMsg == 'requestSubscribeMessage:ok') {
                  if (res[tmpId] === 'accept') {
                    that.collectAccept();
                    console.log('requestSubscribeMessage 订阅消息成功');
                  } else {
                    console.log('requestSubscribeMessage 订阅消息失败')
                  }
                }
              },
              fail: res => {
                console.log('fail', res)
              }
            })
          }
        }
      })
    })
  },
   
  collectAccept(){
    app.util.request({
      url: 'auth/session/subscribeMes',
      data: { m: 'cm_video_alarm' },
      success: res => {
        console.log(res)
      }
    })
  }
});
